#!/bin/bash

# =============================================================================
# Dify 生产环境一键部署脚本 v2.0 (2025增强版)
# 支持 Ubuntu 20.04/22.04 LTS, CentOS 7/8, RHEL 7/8
# 增强功能：智能config目录管理 + 零停机部署 + 完善错误处理
# =============================================================================

set -euo pipefail
IFS=$'\n\t'

# --- 全局配置 ---
SCRIPT_VERSION="2.0.0"
DIFY_VERSION="0.6.13"
MIN_RAM_GB=4
MIN_DISK_GB=20
DEPLOY_USER="root"

# 脚本和部署目录分离
SCRIPT_DIR=$(dirname "$(readlink -f "$0")")  # 脚本实际位置
DEPLOY_DIR="/root/dify"                      # 部署目标目录
DATA_DIR="/root/dify_data"                   # 独立的数据目录，不会被清理

# Gitee 仓库配置
GITEE_REPO="git@gitee.com:dd0129/dify_test.git"

# --- 颜色输出 ---
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
EMOJI_SUCCESS="✅"
EMOJI_ERROR="❌"
EMOJI_WARNING="⚠️"
EMOJI_INFO="ℹ️"

# --- 日志函数 ---
log_info() {
    echo -e "${BLUE}${EMOJI_INFO} [INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}${EMOJI_SUCCESS} [SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}${EMOJI_WARNING} [WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}${EMOJI_ERROR} [ERROR]${NC} $1"
}

log_header() {
    echo
    echo -e "${BLUE}======================================${NC}"
    echo -e "${BLUE}  $1${NC}"
    echo -e "${BLUE}======================================${NC}"
    echo
}

# --- 错误处理和回滚 ---
trap 'handle_error $LINENO' ERR
handle_error() {
    log_error "脚本在第 $1 行执行失败"
    log_error "请检查上面的错误信息并修复问题后重新运行"
    
    # 尝试自动回滚
    if [[ -n "${BACKUP_CREATED:-}" ]]; then
        log_info "尝试自动回滚到备份状态..."
        rollback_deployment || log_warning "自动回滚失败，请手动检查"
    fi
    exit 1
}

# --- 系统检测函数 ---
detect_os() {
    if [[ -f /etc/os-release ]]; then
        source /etc/os-release
        OS=$ID
        VERSION=$VERSION_ID
    else
        log_error "无法检测操作系统类型"
        exit 1
    fi
    log_info "检测到操作系统: $OS $VERSION"
}

check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "此脚本需要 root 权限运行"
        log_info "请使用: sudo bash $0"
        exit 1
    fi
}

check_system_requirements() {
    log_info "检查系统资源要求..."
    
    # 检查内存
    local ram_gb=$(free -g | awk '/^Mem:/{print $2}')
    if (( ram_gb < MIN_RAM_GB )); then
        log_error "内存不足，需要至少 ${MIN_RAM_GB}GB，当前: ${ram_gb}GB"
        exit 1
    fi
    
    # 检查磁盘空间
    local disk_gb=$(df -BG / | awk 'NR==2 {print $4}' | sed 's/G//')
    if (( disk_gb < MIN_DISK_GB )); then
        log_error "磁盘空间不足，需要至少 ${MIN_DISK_GB}GB，当前可用: ${disk_gb}GB"
        exit 1
    fi
    
    log_success "系统资源检查通过 (内存: ${ram_gb}GB, 磁盘: ${disk_gb}GB)"
}

# --- 备份现有部署 ---
backup_existing_deployment() {
    if [[ -d "$DEPLOY_DIR" ]]; then
        local backup_dir="/root/dify_backup_$(date +%Y%m%d_%H%M%S)"
        log_info "备份现有部署到: $backup_dir"
        
        # 停止服务
        if systemctl is-active --quiet dify 2>/dev/null; then
            log_info "停止现有Dify服务..."
            systemctl stop dify || log_warning "停止服务失败，继续备份"
        fi
        
        # 备份config目录（重要配置）
        if [[ -d "$DEPLOY_DIR/config" ]]; then
            mkdir -p "$backup_dir"
            cp -r "$DEPLOY_DIR/config" "$backup_dir/" || log_warning "配置备份失败"
            log_success "配置文件已备份"
            export BACKUP_CREATED="$backup_dir"
        fi
    fi
}

# --- 回滚部署 ---
rollback_deployment() {
    if [[ -n "${BACKUP_CREATED:-}" && -d "$BACKUP_CREATED" ]]; then
        log_info "执行回滚操作..."
        
        # 恢复配置
        if [[ -d "$BACKUP_CREATED/config" ]]; then
            mkdir -p "$DEPLOY_DIR"
            cp -r "$BACKUP_CREATED/config" "$DEPLOY_DIR/" || return 1
            log_success "配置已恢复"
        fi
        
        # 尝试重启服务
        if systemctl is-enabled --quiet dify 2>/dev/null; then
            systemctl start dify || log_warning "服务重启失败"
        fi
        
        log_success "回滚完成"
        return 0
    fi
    return 1
}

# --- 系统更新 (增强版) ---
update_system() {
    log_info "更新系统包..."
    
    case $OS in
        ubuntu|debian)
            export DEBIAN_FRONTEND=noninteractive
            
            # 修复可能的损坏包
            apt-get --fix-broken install -y || true
            
            # 更新软件包列表
            log_info "更新软件包列表..."
            apt-get update || log_warning "软件包列表更新失败，继续执行..."
            
            # 升级系统包
            log_info "升级系统包..."
            apt-get upgrade -y || log_warning "系统包升级失败，继续执行..."
            
            # 安装基础包
            log_info "安装基础系统包..."
            apt-get install -y curl wget gnupg lsb-release ca-certificates \
                software-properties-common apt-transport-https \
                net-tools git vim jq || log_warning "某些基础包安装失败，继续执行..."
            
            # 安装额外工具包（容错安装）
            log_info "安装额外工具包..."
            for package in ufw fail2ban htop iotop; do
                apt-get install -y "$package" || log_warning "$package 安装失败，跳过..."
            done
            ;;
        centos|rhel|rocky|almalinux)
            # 处理CentOS 8 EOL问题
            if [[ "$OS" == "centos" && "$VERSION" == "8" ]]; then
                log_info "处理CentOS 8 EOL仓库问题..."
                mkdir -p /etc/yum.repos.d/backup
                cp /etc/yum.repos.d/CentOS-*.repo /etc/yum.repos.d/backup/ 2>/dev/null || true
                
                sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*.repo 2>/dev/null || true
                sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-*.repo 2>/dev/null || true
                
                yum clean all 2>/dev/null || true
            fi
            
            # 更新系统包
            yum update -y || log_warning "系统更新失败，继续执行..."
            
            # 安装基础包
            yum install -y curl wget ca-certificates net-tools git vim jq || log_warning "某些基础包安装失败，继续执行..."
            
            # 配置EPEL仓库
            if ! rpm -qa | grep -q epel-release; then
                yum install -y epel-release || log_warning "EPEL仓库安装失败"
            fi
            
            # 安装额外工具包
            for package in firewalld gnupg2 fail2ban htop iotop; do
                yum install -y "$package" || {
                    log_warning "$package 安装失败，尝试替代包..."
                    case "$package" in
                        iotop) yum install -y python3-iotop 2>/dev/null || true ;;
                        gnupg2) yum install -y gnupg 2>/dev/null || true ;;
                    esac
                }
            done
            ;;
        *)
            log_error "不支持的操作系统: $OS"
            exit 1
            ;;
    esac
    
    log_success "系统更新完成"
}

# --- 验证SSH密钥配置 ---
verify_ssh_config() {
    log_info "验证SSH配置..."
    
    if [[ ! -d "/root/.ssh" ]]; then
        log_warning "SSH配置目录不存在，创建中..."
        mkdir -p /root/.ssh
        chmod 700 /root/.ssh
    fi
    
    if [[ ! -f "/root/.ssh/id_rsa" && ! -f "/root/.ssh/id_ed25519" ]]; then
        log_warning "未找到SSH密钥，请确保已配置SSH密钥以访问 $GITEE_REPO"
    else
        log_success "SSH配置验证通过"
    fi
}

# --- 安装和配置 Docker (2025增强版) ---
install_docker() {
    log_info "安装 Docker..."
    
    if command -v docker &> /dev/null; then
        log_success "Docker 已安装，版本: $(docker --version)"
    else
        # 使用官方安装脚本
        log_info "下载并执行Docker官方安装脚本..."
        curl -fsSL https://get.docker.com -o get-docker.sh
        bash get-docker.sh
        rm -f get-docker.sh
        
        # 启动服务
        systemctl enable docker
        systemctl start docker
        
        log_success "Docker 安装完成: $(docker --version)"
    fi
    
    # 验证Docker Compose
    if ! docker compose version &> /dev/null; then
        log_error "Docker Compose 不可用，请检查Docker安装"
        exit 1
    fi
    
    log_success "Docker Compose 可用: $(docker compose version --short)"
}

# --- 配置 Docker 生产设置 (2025优化版) ---
configure_docker() {
    log_info "配置 Docker 生产环境设置..."
    
    mkdir -p /etc/docker
    
    # 2025年推荐的Docker daemon配置
    cat > /etc/docker/daemon.json << 'EOF'
{
  "registry-mirrors": [
    "https://docker.m.daocloud.io",
    "https://docker.1ms.run",
    "https://docker.chenby.cn",
    "https://dockerpull.org"
  ],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  },
  "storage-driver": "overlay2",
  "live-restore": true,
  "userland-proxy": false,
  "experimental": false,
  "default-ulimits": {
    "nofile": {
      "Name": "nofile",
      "Hard": 65536,
      "Soft": 65536
    }
  },
  "features": {
    "buildkit": true
  },
  "builder": {
    "gc": {
      "enabled": true,
      "defaultKeepStorage": "20GB"
    }
  }
}
EOF
    
    # 重启Docker服务
    systemctl restart docker
    sleep 5
    
    # 验证配置
    if docker info > /dev/null 2>&1; then
        log_success "Docker 生产配置完成并验证通过"
    else
        log_error "Docker配置验证失败"
        exit 1
    fi
}

# --- 配置防火墙 ---
configure_firewall() {
    log_info "配置防火墙..."
    
    case $OS in
        ubuntu|debian)
            if command -v ufw &> /dev/null; then
                ufw --force reset
                ufw default deny incoming
                ufw default allow outgoing
                ufw allow ssh
                ufw allow 80/tcp
                ufw allow 443/tcp
                ufw --force enable
                log_success "UFW防火墙配置完成"
            else
                log_warning "UFW未安装，跳过防火墙配置"
            fi
            ;;
        centos|rhel|rocky|almalinux)
            if command -v firewall-cmd &> /dev/null; then
                systemctl enable firewalld
                systemctl start firewalld
                firewall-cmd --permanent --add-service=ssh
                firewall-cmd --permanent --add-service=http
                firewall-cmd --permanent --add-service=https
                firewall-cmd --reload
                log_success "firewalld防火墙配置完成"
            else
                log_warning "firewalld未安装，跳过防火墙配置"
            fi
            ;;
    esac
}

# --- 智能项目部署 (零停机更新) ---
deploy_project_intelligently() {
    log_info "执行智能项目部署..."
    
    # 备份现有部署
    backup_existing_deployment
    
    # 创建临时部署目录
    local temp_deploy_dir="${DEPLOY_DIR}_new_$(date +%s)"
    log_info "创建临时部署目录: $temp_deploy_dir"
    
    # 克隆到临时目录
    log_info "克隆项目到临时目录..."
    git clone "$GITEE_REPO" "$temp_deploy_dir" || {
        log_error "Git克隆失败，请检查网络连接和SSH密钥配置"
        exit 1
    }
    
    # 迁移现有配置
    if [[ -d "$DEPLOY_DIR/config" ]]; then
        log_info "迁移现有配置到新部署..."
        cp -r "$DEPLOY_DIR/config" "$temp_deploy_dir/" || log_warning "配置迁移失败"
    fi
    
    # 检查服务是否运行
    local services_running=false
    if [[ -d "$DEPLOY_DIR" ]] && systemctl is-active --quiet dify 2>/dev/null; then
        services_running=true
        log_info "检测到服务正在运行，准备零停机更新..."
    fi
    
    # 原子性替换部署目录
    if [[ -d "$DEPLOY_DIR" ]]; then
        local old_deploy_dir="${DEPLOY_DIR}_old_$(date +%s)"
        mv "$DEPLOY_DIR" "$old_deploy_dir" || {
            log_error "无法备份现有部署目录"
            rm -rf "$temp_deploy_dir"
            exit 1
        }
    fi
    
    mv "$temp_deploy_dir" "$DEPLOY_DIR" || {
        log_error "无法替换部署目录"
        # 尝试恢复
        [[ -d "$old_deploy_dir" ]] && mv "$old_deploy_dir" "$DEPLOY_DIR"
        exit 1
    }
    
    # 清理旧目录
    [[ -d "${old_deploy_dir:-}" ]] && rm -rf "$old_deploy_dir"
    
    log_success "项目部署完成"
}

# --- 智能配置管理 ---
manage_configurations() {
    log_info "管理配置文件..."
    
    local config_dir="$DEPLOY_DIR/config"
    mkdir -p "$config_dir"
    
    # 检查是否已有配置文件
    if [[ -f "$config_dir/.env.production" ]]; then
        log_info "发现现有配置文件，验证配置完整性..."
        
        # 验证关键配置项
        local missing_configs=()
        for key in SECRET_KEY DB_PASSWORD REDIS_PASSWORD; do
            if ! grep -q "^$key=" "$config_dir/.env.production" 2>/dev/null; then
                missing_configs+=("$key")
            fi
        done
        
        if [[ ${#missing_configs[@]} -gt 0 ]]; then
            log_warning "配置文件缺少关键项: ${missing_configs[*]}"
            log_info "重新生成配置文件..."
            generate_production_configs
        else
            log_success "现有配置验证通过，保留使用"
        fi
    else
        log_info "未找到配置文件，生成新配置..."
        generate_production_configs
    fi
    
    # 生成nginx配置
    generate_nginx_config
}

# --- 生成生产环境配置 ---
generate_production_configs() {
    log_info "生成生产环境配置文件..."
    
    local config_dir="$DEPLOY_DIR/config"
    mkdir -p "$config_dir"
    
    # 生成随机密钥
    local secret_key=$(openssl rand -base64 42)
    local db_password=$(openssl rand -base64 32 | tr -d '+/=' | cut -c1-24)
    local redis_password=$(openssl rand -base64 32 | tr -d '+/=' | cut -c1-24)
    
    # 生产环境变量配置
    cat > "$config_dir/.env.production" << EOF
# =============================================================================
# Dify 生产环境配置文件
# 由部署脚本自动生成 - $(date)
# =============================================================================

# --- 应用配置 ---
CONSOLE_WEB_URL=http://localhost
CONSOLE_API_URL=http://localhost
SERVICE_API_URL=http://localhost
APP_WEB_URL=http://localhost
APP_API_URL=http://localhost

# --- 安全配置 ---
SECRET_KEY=$secret_key
ENCRYPT_PUBLIC_KEY=

# --- 数据库配置 ---
DB_USERNAME=dify
DB_PASSWORD=$db_password
DB_HOST=postgres
DB_PORT=5432
DB_DATABASE=dify

# --- Redis配置 ---
REDIS_HOST=redis
REDIS_PORT=6379
REDIS_PASSWORD=$redis_password
REDIS_USE_SSL=false

# --- 向量数据库配置 ---
VECTOR_STORE=weaviate
WEAVIATE_ENDPOINT=http://weaviate:8080

# --- 邮件配置 ---
MAIL_TYPE=
MAIL_DEFAULT_SEND_FROM=noreply@your-domain.com

# --- 代码执行配置 ---
CODE_EXECUTION_ENDPOINT=http://sandbox:8194
CODE_EXECUTION_API_KEY=dify-sandbox

# --- Session配置 ---
SESSION_TYPE=redis
SESSION_REDIS_HOST=redis
SESSION_REDIS_PORT=6379
SESSION_REDIS_PASSWORD=$redis_password

# --- Celery配置 ---
CELERY_BROKER_URL=redis://:$redis_password@redis:6379/1

# --- 存储配置 ---
STORAGE_TYPE=local
STORAGE_LOCAL_PATH=storage

# --- 安全代理配置 ---
HTTP_PROXY=http://ssrf_proxy:3128
HTTPS_PROXY=http://ssrf_proxy:3128

# --- 监控配置 ---
SENTRY_DSN=
SENTRY_TRACES_SAMPLE_RATE=1.0
SENTRY_PROFILES_SAMPLE_RATE=1.0

# --- 高级配置 ---
DEBUG=false
LOG_LEVEL=INFO
LOG_FILE=
MIGRATION_ENABLED=true
EDITION=SELF_HOSTED

# --- 通义千问配置 ---
TONGYI_DASHSCOPE_API_KEY=sk-4ee0b71b1bbd4e48a5e46810278ccb14
EOF
    
    # 设置配置文件权限
    chmod 600 "$config_dir/.env.production"
    chown root:root "$config_dir/.env.production"
    
    log_success "生产配置文件生成完成"
}

# --- 生成Nginx配置 ---
generate_nginx_config() {
    log_info "生成Nginx配置..."
    
    local nginx_dir="$DEPLOY_DIR/config/nginx"
    mkdir -p "$nginx_dir"
    
    # 2025年优化的Nginx配置
    cat > "$nginx_dir/nginx.conf" << 'EOF'
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # 日志格式
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;

    # 性能优化
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    client_max_body_size 50M;
    client_body_timeout 60s;
    client_header_timeout 60s;

    # 压缩配置
    gzip on;
    gzip_vary on;
    gzip_min_length 1000;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/json
        application/javascript
        application/xml+rss
        application/atom+xml
        image/svg+xml;

    # 后端服务配置
    upstream api_backend {
        server api:5001;
        keepalive 32;
    }

    upstream web_backend {
        server web:3000;
        keepalive 32;
    }

    # 主服务器配置
    server {
        listen 80;
        server_name _;

        # 安全头
        add_header X-Content-Type-Options nosniff;
        add_header X-Frame-Options DENY;
        add_header X-XSS-Protection "1; mode=block";

        # API路由
        location ~ ^/(api|console/api|v1|files) {
            proxy_pass http://api_backend;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            
            proxy_connect_timeout 60s;
            proxy_send_timeout 60s;
            proxy_read_timeout 300s;
            
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            
            # 缓冲设置
            proxy_buffering on;
            proxy_buffer_size 4k;
            proxy_buffers 8 4k;
        }

        # Web应用路由
        location / {
            proxy_pass http://web_backend;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            
            proxy_connect_timeout 60s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
            
            proxy_http_version 1.1;
            proxy_set_header Connection "";
        }

        # 健康检查
        location /nginx-health {
            access_log off;
            return 200 "healthy\n";
            add_header Content-Type text/plain;
        }

        # 静态文件缓存
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
            add_header Vary Accept-Encoding;
        }
    }
}
EOF
    
    log_success "Nginx配置生成完成"
}

# --- 创建和管理数据目录 ---
create_data_directories() {
    log_info "创建和配置数据目录..."
    
    # 创建独立数据目录
    mkdir -p "$DATA_DIR"/{postgres,redis,weaviate,uploads}
    mkdir -p "$DEPLOY_DIR"/{logs,backups}
    mkdir -p "$DEPLOY_DIR/logs/nginx"
    
    # 设置目录权限以支持Docker容器
    log_info "设置数据目录权限..."
    
    # PostgreSQL (UID 999)
    chown -R 999:999 "$DATA_DIR/postgres"
    chmod -R 750 "$DATA_DIR/postgres"
    
    # Redis (UID 999)  
    chown -R 999:999 "$DATA_DIR/redis"
    chmod -R 750 "$DATA_DIR/redis"
    
    # Weaviate (UID 1000)
    chown -R 1000:1000 "$DATA_DIR/weaviate"
    chmod -R 755 "$DATA_DIR/weaviate"
    
    # 上传目录 (UID 1001)
    chown -R 1001:1001 "$DATA_DIR/uploads"
    chmod -R 755 "$DATA_DIR/uploads"
    
    # 其他目录
    chown -R root:root "$DEPLOY_DIR"/{logs,backups,config}
    chmod -R 755 "$DEPLOY_DIR"/{logs,backups,config}
    
    log_success "数据目录权限配置完成"
    log_info "数据目录位置: $DATA_DIR (独立持久化)"
}

# --- 配置系统服务 ---
configure_system_service() {
    log_info "配置系统服务..."
    
    # 安装维护脚本
    if [[ -f "$DEPLOY_DIR/maintenance.sh" ]]; then
        cp "$DEPLOY_DIR/maintenance.sh" /usr/local/bin/dify-maintenance
        chmod +x /usr/local/bin/dify-maintenance
    fi
    
    # 创建systemd服务
    cat > /etc/systemd/system/dify.service << EOF
[Unit]
Description=Dify Production Service
Documentation=https://docs.dify.ai/
Requires=docker.service
After=docker.service network-online.target
Wants=network-online.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/bin/bash -c 'cd $DEPLOY_DIR && docker compose -f docker-compose.production.yml up -d'
ExecStop=/bin/bash -c 'cd $DEPLOY_DIR && docker compose -f docker-compose.production.yml down'
ExecReload=/bin/bash -c 'cd $DEPLOY_DIR && docker compose -f docker-compose.production.yml restart'
TimeoutStartSec=300
TimeoutStopSec=60
User=root
Group=root
WorkingDirectory=$DEPLOY_DIR

[Install]
WantedBy=multi-user.target
EOF
    
    # 重新加载systemd并启用服务
    systemctl daemon-reload
    systemctl enable dify
    
    log_success "系统服务配置完成"
}

# --- 启动服务 ---
start_services() {
    log_info "启动Dify服务..."
    
    cd "$DEPLOY_DIR"
    
    # 拉取最新镜像
    log_info "拉取Docker镜像..."
    docker compose -f docker-compose.production.yml pull || log_warning "部分镜像拉取失败，继续启动..."
    
    # 启动服务
    log_info "启动所有服务..."
    systemctl start dify
    
    # 等待服务启动
    log_info "等待服务完全启动..."
    sleep 30
    
    # 检查服务状态
    docker compose -f docker-compose.production.yml ps
    
    log_success "Dify服务启动完成"
}

# --- 验证部署 ---
verify_deployment() {
    log_info "验证部署状态..."
    
    cd "$DEPLOY_DIR"
    
    # 检查容器状态
    local healthy_containers=$(docker compose -f docker-compose.production.yml ps --format json 2>/dev/null | jq -r '. | select(.Health == "healthy" or (.State == "running" and .Health == null)) | .Service' | wc -l)
    local total_containers=$(docker compose -f docker-compose.production.yml ps --format json 2>/dev/null | jq -r '.Service' | wc -l)
    
    echo ""
    echo "=== 部署验证结果 ==="
    echo "健康容器数: $healthy_containers/$total_containers"
    
    # 等待服务完全就绪
    log_info "等待服务完全就绪..."
    sleep 15
    
    # 测试Web访问
    if curl -f -s http://localhost > /dev/null 2>&1; then
        log_success "Web服务访问正常: http://localhost"
    else
        log_warning "Web服务访问失败，可能还在启动中"
    fi
    
    # 测试API访问
    if curl -f -s http://localhost/console/api/setup > /dev/null 2>&1; then
        log_success "API服务访问正常"
    else
        log_warning "API服务访问失败，可能还在启动中"
    fi
    
    # 显示服务详细状态
    echo ""
    echo "=== 详细服务状态 ==="
    docker compose -f docker-compose.production.yml ps
    
    # 检查关键服务日志
    log_info "检查关键服务状态..."
    local failed_services=()
    
    for service in api web postgres redis; do
        if ! docker compose -f docker-compose.production.yml ps --format json | jq -r '. | select(.Service == "'$service'") | .State' | grep -q running; then
            failed_services+=("$service")
        fi
    done
    
    if [[ ${#failed_services[@]} -gt 0 ]]; then
        log_warning "以下关键服务未正常运行: ${failed_services[*]}"
        log_info "请检查服务日志: docker compose -f docker-compose.production.yml logs <service-name>"
    else
        log_success "所有关键服务运行正常"
    fi
}

# --- 生成部署报告 ---
generate_deployment_report() {
    log_info "生成部署报告..."
    
    local report_file="$DEPLOY_DIR/deployment-report-$(date +%Y%m%d_%H%M%S).txt"
    
    cat > "$report_file" << EOF
================================================================================
Dify 生产环境部署报告 v$SCRIPT_VERSION
================================================================================

部署时间: $(date)
脚本版本: $SCRIPT_VERSION  
Dify版本: $DIFY_VERSION
操作系统: $OS $VERSION
部署目录: $DEPLOY_DIR
数据目录: $DATA_DIR
仓库地址: $GITEE_REPO

服务状态:
$(cd "$DEPLOY_DIR" && docker compose -f docker-compose.production.yml ps 2>/dev/null || echo "获取服务状态失败")

系统资源:
CPU核心数: $(nproc)
总内存: $(free -h | grep '^Mem:' | awk '{print $2}')
可用磁盘: $(df -h / | tail -1 | awk '{print $4}')

访问地址:
- Web管理界面: http://localhost
- API接口文档: http://localhost/console/api
- 健康检查: http://localhost/nginx-health

管理命令:
- 启动所有服务: systemctl start dify
- 停止所有服务: systemctl stop dify
- 重启所有服务: systemctl restart dify
- 查看服务状态: systemctl status dify
- 查看容器状态: docker compose -f docker-compose.production.yml ps
- 查看服务日志: docker compose -f docker-compose.production.yml logs <service>
- 维护工具: dify-maintenance help (如果可用)

重要文件路径:
- 主配置文件: $DEPLOY_DIR/config/.env.production
- Nginx配置: $DEPLOY_DIR/config/nginx/nginx.conf
- Docker配置: $DEPLOY_DIR/docker-compose.production.yml
- 服务配置: /etc/systemd/system/dify.service

数据目录 (持久化):
- PostgreSQL: $DATA_DIR/postgres
- Redis: $DATA_DIR/redis  
- Weaviate: $DATA_DIR/weaviate
- 上传文件: $DATA_DIR/uploads

日志目录:
- 应用日志: $DEPLOY_DIR/logs
- Nginx日志: $DEPLOY_DIR/logs/nginx
- 系统日志: journalctl -u dify

备份目录:
- 自动备份: $DEPLOY_DIR/backups

操作建议:
1. 首次使用请访问 http://localhost 进行初始化设置
2. 如需HTTPS，请配置SSL证书并更新Nginx配置
3. 根据实际需要修改 $DEPLOY_DIR/config/.env.production
4. 定期备份数据目录: $DATA_DIR
5. 监控服务状态: systemctl status dify
6. 查看实时日志: docker compose -f docker-compose.production.yml logs -f

故障排除:
- 如果服务启动失败，请检查: docker compose -f docker-compose.production.yml logs
- 如果端口冲突，请修改docker-compose.production.yml中的端口映射
- 如果数据库连接失败，请检查$DATA_DIR权限设置
- 如果镜像拉取失败，请检查网络连接和Docker镜像源配置

安全提醒:
- 默认配置仅适用于内网环境
- 生产环境请配置HTTPS和防火墙
- 请及时更改默认密钥和密码
- 建议配置监控和日志收集

================================================================================
EOF
    
    chmod 644 "$report_file"
    log_success "部署报告已生成: $report_file"
}

# --- 主函数 ---
main() {
    log_header "Dify 生产环境一键部署脚本 v$SCRIPT_VERSION"
    
    log_info "脚本执行位置: $SCRIPT_DIR"
    log_info "部署目标目录: $DEPLOY_DIR"
    log_info "数据存储目录: $DATA_DIR"
    log_info "解决方案特性: 智能配置管理 + 零停机部署 + 完善错误处理"
    
    echo ""
    log_info "开始执行Dify生产环境部署..."
    echo ""
    
    # 执行部署步骤
    check_root
    detect_os
    check_system_requirements
    
    # 系统环境准备
    update_system
    verify_ssh_config
    install_docker
    configure_docker
    configure_firewall
    
    # 项目部署
    deploy_project_intelligently
    manage_configurations
    create_data_directories
    
    # 服务配置和启动
    configure_system_service
    start_services
    verify_deployment
    
    # 生成报告
    generate_deployment_report
    
    echo ""
    log_header "🎉 Dify 生产环境部署完成！"
    echo ""
    log_success "📋 访问信息："
    echo "   🌐 Web管理界面: http://localhost"
    echo "   🔧 API接口: http://localhost/console/api"
    echo "   ❤️  健康检查: http://localhost/nginx-health"
    echo ""
    log_success "📋 管理命令："
    echo "   systemctl start|stop|restart|status dify"
    echo "   docker compose -f docker-compose.production.yml logs <service>"
    echo ""
    log_success "📁 重要目录："
    echo "   项目目录: $DEPLOY_DIR"
    echo "   数据目录: $DATA_DIR (持久化)"
    echo "   配置文件: $DEPLOY_DIR/config/.env.production"
    echo ""
    log_info "📖 详细信息请查看部署报告文件"
    echo ""
}

# --- 脚本入口 ---
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi
